package org.dim.config.parse;

import org.dim.config.Bean;
import org.dim.config.Property;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ConfigManager {
    //读取配置文件并返回结果
    public static Map<String, Bean> getConfig(String path){
        Map<String,Bean>map=new HashMap<>();
        Document doc=null;
        //dom4j实现
           //创建解析
        SAXReader reader=new SAXReader();

        //InputStream is=ConfigManager.class.getResourceAsStream("applicationContext.xml");
        try {
            //加载配置
            InputStream is=new FileInputStream(path);
            doc=reader.read(is);
        } catch (DocumentException e) {
            e.printStackTrace();
            throw new RuntimeException("检查xml配置是否正确");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        //定义path
        String xpath="//bean";
          //对bean遍历
          List<Element> list=doc.selectNodes(xpath);
          if (list!=null){
              for (Element beanEle:list){
                  Bean bean=new Bean();
                  String name= String.valueOf(beanEle.attributeValue("name"));
                  String className= String.valueOf(beanEle.attributeValue("class"));
                  //将name/class封装到bean
                  bean.setName(name);
                  bean.setClassName(className);
                  List<Element>children= (List<Element>) beanEle.elements("property");
                  if (children!=null){
                      for (Element child:children){
                          //将bean下的property的name/value/ref封装到property，再将其装到bean中
                          //注意顺序不能乱
                          Property prop=new Property(child.attributeValue("name"),
                                  child.attributeValue("value"),
                                 child.attributeValue("ref"));
                          bean.getProperties().add(prop);
                      }
                  }
                  //将bean装入map中
                  map.put(name,bean);
              }
          }
          //返回map结果
        return map;
    }
}
